package br.com.hbt.thread;

public class AccountDanger implements Runnable {

    private Account acct = new Account();

    public static void main(String[] args) {
        AccountDanger r = new AccountDanger();
        Thread one = new Thread(r);
        Thread two = new Thread(r);
        one.setName("Fred");
        two.setName("Lucy");
        one.start();
        two.start();
    }

    @Override
    public void run() {

        for (int j = 0; j < 5; j++) {

            makeWithDrawal(10);
        }

        if (acct.getBalance() < 0) {
            System.out.println("Saldo Insuficiente" + acct.getBalance());
        }
    }

    private synchronized void makeWithDrawal(int amount) {

        if (acct.getBalance() >= amount) {
            System.out.println("" + Thread.currentThread().getName() + " vai sacar." + acct.getBalance());
            try {

                Thread.sleep(500);
            } catch (InterruptedException e) {}
            acct.withdraw(amount);
            System.out.println("" + Thread.currentThread().getName() + " completou o saque. " + acct.getBalance());
        } else {
            System.out.println("Não há saldo suficiente para " + Thread.currentThread().getName() + " para sacar. " + acct.getBalance());
        }
    }

}
